package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class PassportApiController {


    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     * @param userInfo
     * @param request
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request) {

        UserInfo user = userService.login(userInfo);
        if (user != null) {
            String token = UUID.randomUUID().toString();
            String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
//            防止伪造登录
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("ip", IpUtil.getIpAddress(request));
            jsonObject.put("userId", user.getId().toString());

            redisTemplate.opsForValue().set(userKey, jsonObject, RedisConst.USER_CART_EXPIRE, TimeUnit.SECONDS);

            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("nickName", user.getName());
            return Result.ok(map);
        }else {
            return Result.fail("登录失败");
        }

    }

    /**
     * 用户退出
     * @param request
     * @return
     */
    @GetMapping("logout")
    public Result logout(HttpServletRequest request){

//        获取请求头数据token
        String token = request.getHeader("token");

        String userKey = RedisConst.USER_LOGIN_KEY_PREFIX+token;

        redisTemplate.delete(userKey);

        return Result.ok();
    }

}
